//
// Sound data class for OpenAL
//

#ifndef	__SOUND_DATA__
#define	__SOUND_DATA__

#include	<stdio.h>
#include    <math.h>
#include	"../utils/TypeDefs.h"
#include "../output/Sound.h"

class	Data;

class	SoundData
{
protected:
	Data  * data;
	FILE  * fp;
	int		numChannels;
	int		frequency;
	int		bitsPerSample;
    bool	ok;
    uint64 AudioStartPos; //byte from which playing was started
    unsigned ProcessedBuffersCount;
    friend Sound;
public:
	SoundData ( Data * theData );
	SoundData ( const char * theFileName );
	virtual	~SoundData ();


	int	getNumChannels () const
	{
		return numChannels;
	}

	int	getFrequency () const
	{
		return frequency;
	}

	int	getBitsPerSample () const
	{
		return bitsPerSample;
	}
	
	virtual	bool	isOk () const;

											// get size in bytes of unpacked audio data
	virtual	int		getSize () const = 0;

    uint64  bytes2secs(uint64 bytes)
    {
        if (frequency == 0 ||  numChannels == 0 ||(bitsPerSample/ 8) == 0)
            return 0;
        double res = double(bytes) / (frequency *  numChannels * (bitsPerSample) / 8);
        return lround(res);
    }

    uint64 secs2bytes(uint64 secs)
    {
        return secs * (frequency *  numChannels * (bitsPerSample) / 8);
    }

    inline uint64 getDuration()
    {
        return bytes2secs(getSize());
    }

											// fill buffer with next audio data
	virtual	int	read ( byte * buf, int size = -1 ) = 0;

											// position in sound (in seconds)
    virtual	bool	seek ( double time )
    {
        AudioStartPos = secs2bytes(time);
        ProcessedBuffersCount = 0;
        return false;
    }
											// whether we're at end of sound data
    virtual	bool	atEnd () const;

};

#endif
